import aiomysql
from fastapi import APIRouter, Form, HTTPException, Query

from apps.utils.sql_conn import get_db_cursor

fabric = APIRouter()


@fabric.post("/fabric/set_allow_company", response_description="设置用户允许的公司")
async def set_allow_company(
        email: str = Form(...),
        value: str = Form(...)  # 接收1、2或1,2格式的值
):
    """
    设置用户允许的公司：
    1. 接收邮箱和值（1、2或1,2）
    2. 根据值映射为对应的MSP名称
    3. 更新user_info表中对应邮箱用户的allowcompany字段
    """
    # 验证输入值的有效性
    valid_values = {"1", "2", "1,2", "2,1"}
    if value not in valid_values:
        raise HTTPException(
            status_code=400,
            detail="无效的值，请输入1、2或1,2"
        )

    # 映射值到MSP名称
    msp_map = {
        "1": "Org1MSP",
        "2": "Org2MSP"
    }

    # 处理输入值，去重并保持顺序（1优先）
    values = list(set(value.split(',')))  # 去重
    values.sort()  # 排序后1会在2前面
    msp_list = [msp_map[v] for v in values]
    allow_company = ",".join(msp_list)

    async with get_db_cursor() as cursor:
        try:
            # 检查用户是否存在
            await cursor.execute(
                "SELECT id FROM user_info WHERE email = %s",
                (email,)
            )
            user = await cursor.fetchone()
            if not user:
                raise HTTPException(
                    status_code=404,
                    detail="用户不存在"
                )

            # 更新allowcompany字段
            await cursor.execute(
                "UPDATE user_info SET allowcompany = %s WHERE email = %s",
                (allow_company, email)
            )

            return {
                "status": "success",
                "message": "允许的公司设置成功",
                "allow_company": allow_company
            }

        except aiomysql.Error as e:
            raise HTTPException(
                status_code=500,
                detail=f"数据库错误：{e.args[1]}"
            )
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"服务器内部错误：{str(e)}"
            )


@fabric.get("/fabric/get_allow_company", response_description="根据邮箱查询允许的公司")
async def get_allow_company(email: str = Query(..., description="用户邮箱")):
    """
    根据邮箱查询user_info表中对应记录的allowcompany字段值
    """
    async with get_db_cursor() as cursor:
        try:
            # 根据邮箱查询对应的allowcompany字段
            await cursor.execute(
                "SELECT allowcompany FROM user_info WHERE email = %s",
                (email,)
            )
            result = await cursor.fetchone()

            if not result:
                return {
                    "status": "error",
                    "detail": f"未找到邮箱为{email}的用户记录"
                }

            return {
                "status": "success",
                "data": {
                    "email": email,
                    "allowcompany": result['allowcompany']
                }
            }

        except aiomysql.Error as e:
            raise HTTPException(
                status_code=500,
                detail=f"数据库错误：{e.args[1]}"
            )
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"服务器内部错误：{str(e)}"
            )
